package com.qwiki.text;

import java.util.Collections;
import java.util.List;

/**
 * Corresponds to a template reference in wikipedia.
 * 
 * @author xgu
 * 
 * @since May 30, 2012
 */
public class TemplateNode extends Node
{

  @Override
  public String getText()
  {
    return "";
  }

  @Override
  public List<Node> getChildren()
  {
    return Collections.EMPTY_LIST;
  }

  @Override
  public boolean parse(char[] buffer, int start)
  {
    this.start = start;
    this.buffer = buffer;
    if (match(buffer, start, "{{"))
    {
      int i = start + 2;
      int pivot = i;
      TemplateNode node = new TemplateNode();
      while (i < buffer.length)
      {
        // parse nested TemplateNode
        if (node.parse(buffer, i))
        {
          i += node.getLength();
          pivot = i;
          node.parsed = false;
          continue;
        }
        // parse end of TemplateNode
        if (match(buffer, i, "}}"))
        {
          end = i + 2;
          parsed = true;
          return true;
        }
        i++;
      }
      // saw the start but not the end of template node
      // source malformed
      parsed = true;
      end = find(buffer, "\n", pivot);
      end = end < 0 ? buffer.length : end;
      return true;
    }
    return false;
  }

}
